﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sl.Support.McuBytes;

namespace Sl.Forms {
	public partial class StreamOutputRTB : RichTextBox {

		private bool string_mode = false;

		Palette palette = new Palette();
		public bool Record_ascii { get; set; } = true;
		public bool Record_hex { get; set; } = true;
		public bool Record_time { get; set; } = true;
		public bool Record_length { get; set; } = true;
		public bool String_mode {
			get => string_mode;
			set {
				string_mode = value;
				if(string_mode==true) {
					AppendText($"[TEXT]\n");
				} else {
					AppendText($"\n[TEXT_END]\n");
				}
			}
		}

		public StreamOutputRTB() {
			this.ReadOnly = true;
		}




		protected override void OnPaint(PaintEventArgs pe) {
			base.OnPaint(pe);
		}
		public Decoder dc;
		public Encoder ec;
		public void encodingInit(Encoding encode) {
			dc = encode.GetDecoder();
			ec = encode.GetEncoder();
		}
		char[] GetChars = new char[1024];
		public void outputLine(byte[] b,bool is_send, int diff = 0,int len=-1) {
			if(len == -1) {
				len = b.Length - diff;
			}
			if (String_mode == true) {
				if (is_send==false) {
					int char_num = dc.GetChars(b, diff, len == -1 ? b.Length : len, GetChars, 0, false);
					AppendText(new string(GetChars, 0, char_num));
				}
			} else {
				if (Record_time) {
					SelectionColor = palette.time;
					AppendText($"[T={DateTime.Now:HH:mm:ss.fff}]");
				}
				Color color_hex;
				Color color_asc;
				if (is_send) {
					color_hex = SelectionColor = palette.send;
					color_asc = palette.send_a;
					AppendText($"[S]");
				} else {
					color_hex = SelectionColor = palette.recv;
					color_asc = palette.recv_a;
					AppendText($"[R]");
				}

				if (Record_length) {
					SelectionColor = palette.len;
					AppendText($"[L={len}]");
				}
				if (Record_hex) {
					SelectionColor = color_hex;
					AppendText($"<{b.toHexStr(diff, len)}>");
				}
				if (Record_ascii) {
					SelectionColor = color_asc;
					AppendText($" ");
					for (int i = 0; i < len; i++) {
						if ((b[i + diff] >= 0x20) && (b[i + diff] <= 0x7F)) {
							SelectionColor = color_asc;
							AppendText($"{(char)b[i + diff]}");
						} else {
							SelectionColor = color_hex;
							AppendText($"<{b[i + diff].toHexStr()}>");
						}
					}
				}
				AppendText("\n");
				Select(TextLength, 0);
				ScrollToCaret();
			}
		}
		public class Palette {
			public Color time = Color.FromArgb(153, 0, 153);
			public Color len = Color.FromArgb(77, 0, 153);
			public Color recv = Color.FromArgb(77, 38, 0);
			public Color recv_a = Color.FromArgb(128, 64, 0);
			public Color send = Color.FromArgb(0, 38, 77);
			public Color send_a = Color.FromArgb(0, 64, 128);
		}




	}
}
